package com.showsu.editor.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.showsu.editor.entity.dto.MediaGetTranscodeDTO;
import com.showsu.editor.entity.dto.MediaGetVideoTranscodeDTO;
import com.showsu.editor.entity.dto.MediaVideo2AudioDTO;
import com.showsu.editor.entity.dto.MediaVideoInfoDTO;
import com.showsu.editor.service.IMediaService;
import com.showsu.editor.utils.Constant;
import com.showsu.editor.utils.aliyun.*;
import com.showsu.editor.utils.youdao.AudioUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URL;

@Slf4j
@Service
public class MediaServicdeImpl implements IMediaService {

    @Autowired
    private OssUtil ossUtil;

    @Autowired
    private AudioUtil audioUtil;

    @Autowired
    private MTSSubmitJobsUtil mtsSubmitJobsUtil;

    @Autowired
    private ICESubmitJobsUtil iceSubmitJobsUtil;

    @Override
    public MediaVideo2AudioDTO getVideo2Audio(String videoUrl) {
        MediaVideo2AudioDTO result=new MediaVideo2AudioDTO();
        if(videoUrl.contains(Constant.showsuLinkPrefix)){
            result.setVideoUrl(videoUrl);
        }else{
            String fileName= IdUtil.simpleUUID() + ".mp4";
            result.setVideoUrl(ossUtil.uploadHandleWaterDirFile2AliyunOss(videoUrl, fileName));
        }
//        String videoFileKey=result.getVideoUrl().substring(result.getVideoUrl().indexOf(".com/")+5);
        //需要去掉path 前面的/ 才是真正的key
        String videoFileKey= URLUtil.getPath(result.getVideoUrl()).substring(1);;
        String audioFileKey=videoFileKey.replace("."+ FileNameUtil.getSuffix(videoFileKey),".mp3");
        String audioUrl="";
        try {
            String statusCode=mtsSubmitJobsUtil.start(videoFileKey,audioFileKey,"test");
            if(statusCode.equals("200")){
                audioUrl=result.getVideoUrl().replace(videoFileKey,audioFileKey);
            }

        }catch (Exception e){}
        result.setAudioUrl(audioUrl);
        return result;
    }


    @Override
    public String getMediaAudioAsr(String audioUrl) {
        if (StringUtils.isBlank(audioUrl)) {
            return null;
        }
        String result=null;
        try {
            String asrResult=audioUtil.asr60(audioUrl);
            if(!StringUtils.isBlank(asrResult)){
                JSONObject jsonObject= JSON.parseObject(asrResult);
                String errorCode=jsonObject.getString("errorCode");
                if("0".equals(errorCode)){
                    result="";
                    JSONArray jsonArray=jsonObject.getJSONArray("result");
                    if(jsonArray!=null&&jsonArray.size()>0){
                        for(int i=0;i<jsonArray.size();i++){
                            result+=jsonArray.getString(i);
                        }
                    }
                }else if("4304".equals(errorCode)){
                    result="";
                }
            }

        }catch (Exception e){
            log.error("getMediaAudioAsr error, audioUrl:{}, error:{}", audioUrl, e);
        }

        return result;
    }

    @Override
    public String getMediaLongAudioAsr(String audioUrl)  {
        if (StringUtils.isBlank(audioUrl)) {
            return null;
        }
        String result=null;;
        try {
            String asrResult=audioUtil.asrLong(audioUrl);
            if(!StringUtils.isBlank(asrResult)){
                JSONObject jsonObject= JSON.parseObject(asrResult);
                String errorCode=jsonObject.getString("errorCode");
                if("0".equals(errorCode)){
                    result="";
                    JSONArray jsonArray=jsonObject.getJSONArray("result");
                    if(jsonArray!=null&&jsonArray.size()>0){
                        for(int i=0;i<jsonArray.size();i++){
                            JSONObject resultObj=jsonArray.getJSONObject(i);
                            if(resultObj!=null){
                                result+=resultObj.getString("sentence");
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error("getMediaLongAudioAsr error, audioUrl:{}, error:{}", audioUrl, e);
        }
        return result;
    }

    @Override
    public MediaVideoInfoDTO getVideoInfo(String videoUrl) {
        if(!videoUrl.contains(Constant.showsuLinkPrefix)){
            return null;
        }
        MediaVideoInfoDTO result= new MediaVideoInfoDTO();
        //需要去掉path 前面的/ 才是真正的key
        String videoFileKey= URLUtil.getPath(videoUrl).substring(1);;
        MediaInfoJobResult mediaInfoJobResult=iceSubmitJobsUtil.submitSyncMediaInfoJob(videoFileKey);
        if(mediaInfoJobResult!=null){
            BeanUtil.copyProperties(mediaInfoJobResult,result);
        }
        return result;
    }

    @Override
    public MediaGetVideoTranscodeDTO getVideoTranscode(String videoUrl, String format) {
        TranscodeTemplateEnum templateEnum=TranscodeTemplateEnum.getByCode(format);
        if(templateEnum==null){
            return null;
        }
        return this.getVideoTranscode(videoUrl,templateEnum);
    }

    @Override
    public MediaGetVideoTranscodeDTO getVideoTranscode(String videoUrl, TranscodeTemplateEnum format) {
        if(format==null){
            return null;
        }
        MediaGetVideoTranscodeDTO result=new MediaGetVideoTranscodeDTO();
        if(videoUrl.contains(Constant.showsuLinkPrefix)){
            result.setOriginVideoUrl(videoUrl);
        }else{
            String fileName= IdUtil.simpleUUID() + ".mp4";
            result.setOriginVideoUrl(ossUtil.uploadHandleWaterDirFile2AliyunOss(videoUrl, fileName));
        }
        //需要去掉path前面的/字符， 才是真正的key
        String originVideoFileKey=URLUtil.getPath(result.getOriginVideoUrl()).substring(1);
        String videoFileKey=originVideoFileKey.replace(FileNameUtil.getName(originVideoFileKey),format.getCode()+FileNameUtil.getPrefix(originVideoFileKey)+"."+FileNameUtil.getSuffix(originVideoFileKey));
        TranscodeJobResult transcodeJobResult=iceSubmitJobsUtil.submitTranscodeJob(originVideoFileKey,videoFileKey,format,true);
        if(transcodeJobResult!=null
                && StringUtils.isBlank(transcodeJobResult.getErrorCode())
                && "200".equals(transcodeJobResult.getStatusCode())
                &&"Success".equalsIgnoreCase(transcodeJobResult.getStatus())){
            result.setVideoUrl(result.getOriginVideoUrl().replace(originVideoFileKey,videoFileKey));
        }
        return result;
    }

    @Override
    public String getVideoSnapshot(String videoUrl, Integer time, Integer width, Integer height) {
        if(!videoUrl.contains(Constant.showsuLinkPrefix)){
            return null;
        }
        if(time==null){
            return null;
        }
        URL url=URLUtil.toUrlForHttp(videoUrl);
        String imgUrl=videoUrl.replace("?"+url.getQuery(),"");
        imgUrl+="?x-oss-process=video/snapshot,f_jpg,t_"+time;
        if(width!=null){
            imgUrl+=",w_"+width;
        }
        if(height!=null){
            imgUrl+=",h_"+height;
        }
        return imgUrl;
    }

    private String getXhsImageTranscode(String imgUrl, String format){
        String animUrl=imgUrl;
        URL url=null;
        try {
            url=new URL(imgUrl);
        }catch (Exception e){
            return null;
        }
        String query=url.getQuery();
        if(StringUtils.isBlank(query)){
            query="?imageView2/2/w/0/format/jpg/v3";
            String host=url.getProtocol()+"://"+url.getHost();
            String path=url.getPath();
            String fileId=path.substring(path.lastIndexOf('/'));
            int lio=fileId.lastIndexOf("!");
            if(lio!=-1){
                fileId=fileId.substring(0,lio);
            }
            if(path.contains("spectrum")){
                fileId="/spectrum"+fileId;
            }
            if(host.contains("sns-webpic-qc.xhscdn.com")){
                host=host.replace("sns-webpic-qc.xhscdn.com","sns-webpic.xhscdn.com");
            }
            animUrl=host+fileId+query;
        }
        if(query.contains("/jpg")){
            animUrl=animUrl.replace(query,query.replace("/jpg","/"+format));
        }else if(query.contains("/webp")) {
            animUrl=animUrl.replace(query,query.replace("/webp","/"+format));
        }else if(query.contains("/gif")) {
            animUrl=animUrl.replace(query,query.replace("/gif","/"+format));
        }else if(query.contains("/png")) {
            animUrl=animUrl.replace(query,query.replace("/png","/"+format));
        }
        return animUrl;
    }

    @Override
    public MediaGetTranscodeDTO getImageTranscode(String imgUrl, String format)  {
        if(StringUtils.isBlank(imgUrl)){
            return null;
        }
        //小红书的链接 通过小红书 自带的图片转码功能
        if(imgUrl.contains(Constant.xhsFileLinkPrefix0)
                ||imgUrl.contains(Constant.xhsFileLinkPrefix1)){
            String animUrl=this.getXhsImageTranscode(imgUrl,format);
            if(StringUtils.isBlank(animUrl)){
                return null;
            }
            MediaGetTranscodeDTO result=new MediaGetTranscodeDTO();
            String fileName=Constant.xhsAwemeImageTranscodeHandlePrefix + UUID.randomUUID().toString().replaceAll("-","") ;
            fileName+="."+format;
            String ossUrl=ossUtil.uploadHandleWaterDirFile2AliyunOss(animUrl, fileName);
            result.setUrl(ossUrl);
            result.setOriginUrl(imgUrl);
            return result;
        }
        if(imgUrl.contains(Constant.showsuLinkPrefix)){
            URL url=URLUtil.toUrlForHttp(imgUrl);
            String animUrl=imgUrl.replace("?"+url.getQuery(),"");
            animUrl+="?x-oss-process=image/format,"+format;
            MediaGetTranscodeDTO result=new MediaGetTranscodeDTO();
            result.setUrl(animUrl);
            result.setOriginUrl(imgUrl);
            return result;
        }
        return null;
    }


}
